import {
  App,
  Card,
  InputNumber,
  Modal,
  Table,
  Radio,
  Button,
  Tooltip,
} from "antd";
import { TableOutlined, AppstoreOutlined } from "@ant-design/icons";
import React, { useState, useEffect, useMemo, useRef } from "react";
import { useQuery, useInfiniteQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import SearchForm, { ISearchFormRef } from "../searchForm/index.tsx";
import ListTable from "./ListTable.tsx";
import ListItems from "./ListItems.tsx";
import DetailModal, { DetailModalHandles } from "./DetailModal.tsx";
import AddModal, { AddModalHandles } from "./AddModal.tsx";
import EditModal, { EditModalHandles } from "./EditModal.tsx";
import { useApiRequest } from "../../hook/useApiRequest.ts";
import { useConfig } from "../../hook/D8dConfigProvider.tsx";
import ModalForm from "../ModalForm/index.tsx";
import type { GetProps } from "antd";
import * as XLSX from "xlsx";
import useBuildSearchFilters from "../../hook/useBuildSearchFilters.ts";
import type {
  FormItemConfigs,
  DetailFieldConfig,
  TPageRequest,
} from "../../global.ts";
import { useMediaQuery } from "react-responsive";
import InfiniteScroll from "../InfiniteScroll/index.tsx";

type TableColumn = GetProps<typeof Table.Column>;

// 表格列配置类型定义
export interface TableColumnConfig extends TableColumn {
  title: string;
  dataIndex: string;
  key: string;
  render?: (text: any, record: any) => React.ReactNode;
}

// API配置类型定义
export interface ManageApiConfig {
  search?: string;
  edit?: string;
  add?: string;
  delete?: string;
  import?: string;
}

// 组件属性类型定义
interface ManageProps {
  // 关键字搜索字段数组
  searchFields?: string[];
  searchFormFieldConfig?: FormItemConfigs[];
  addFormFieldConfig?: FormItemConfigs[];
  editFormFieldConfig?: FormItemConfigs[];
  // formConfig?: FormConfig[];
  tableColumnConfig?: TableColumnConfig[];
  detailFieldConfig?: DetailFieldConfig[];
  apiConfig?: ManageApiConfig;
  enableAdd?: boolean;
  enableEdit?: boolean;
  enableDelete?: boolean;
  enableExport?: boolean;
  enableImport?: boolean;
  enablePrint?: boolean;
  addFormNode?: React.ReactElement<typeof ModalForm>;
  editFormNode?: React.ReactElement<typeof ModalForm>;
  detailComponent?: React.ComponentType<{ data: any }>;
  addModalWidth?: number;
  editModalWidth?: number;
  detailModalWidth?: number;
  defaultSearchData?: any; // 添加默认搜索条件配置属性
  fixedSearchCondition?: any; // 添加固定搜索条件配置属性
  defaultViewType?: "table" | "list";
  listGridConfig?: {
    desktop: number;
    mobile: number;
  };
  /** 扩展按钮菜单配置 */
  extraButtonMenu?: (record: any) => {
    key: string;
    label: string;
    icon?: React.ReactNode;
    onClick: () => void;
  }[];
  /** 自定义 query key,用于外部刷新数据 */
  queryKey?: string;
  /** 行点击事件 */
  onRowClick?: (record: any) => void;
  /** 自定义新增按钮点击事件 */
  onCustomAdd?: () => void;
  /** 自定义编辑按钮点击事件 */
  onCustomEdit?: (record: any) => void;
}

// 扩展类型定义
interface PageResponse {
  code: number;
  success: boolean;
  data: Record<string, any>[];
  page?: number;
  total?: number;
  message?: string;
  error?: string;
}

interface PageData {
  code: number;
  success: boolean;
  data: Record<string, any>[];
  page?: number;
  total?: number;
  message?: string;
  error?: string;
}

interface MutationData {
  code: number;
  success: boolean;
  message?: string;
  error?: string;
}

interface ApiResponse<T = any> {
  code: number;
  success: boolean;
  data?: T;
  total?: number;
  message?: string;
  error?: string;
}

const Manager: React.FC<ManageProps> = (props: ManageProps) => {
  const { message } = App.useApp();
  const { token } = useConfig();
  const queryClient = useQueryClient();
  const { requestWithToken } = useApiRequest();
  const { buildSearchFilters } = useBuildSearchFilters(props);
  
  // 状态定义
  const [selectedRowKeys, setSelectedRowKeys] = useState<string[]>([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const apiConfig = props.apiConfig ?? ({} as any);
  const tableColumnConfig = props.tableColumnConfig ?? ([] as any);
  const detailFieldConfig = props.detailFieldConfig ?? ([] as any);
  const searchFields = props.searchFields ?? ([] as any);
  const detailModalRef = React.useRef<DetailModalHandles>(null);
  const addModalRef = React.useRef<AddModalHandles>(null);
  const editModalRef = React.useRef<EditModalHandles>(null);
  const searchFormRef = React.useRef<ISearchFormRef>(null);
  const inputRef = useRef<any>(null);
  const [searchData, setSearchData] = useState(props.defaultSearchData ?? {});
  const [viewType, setViewType] = useState<"table" | "list">(props.defaultViewType ?? "table");
  const isMobile = useMediaQuery({ maxWidth: 767 });

  // 固定搜索条件
  const fixedSearchCondition = props.fixedSearchCondition ?? {};

  // 构建 queryKey
  const listQueryKey = useMemo(() => {
    return [props.queryKey || 'managerList', apiConfig.search, searchData, fixedSearchCondition, currentPage, pageSize];
  }, [props.queryKey, apiConfig.search, searchData, fixedSearchCondition, currentPage, pageSize]);

  // PC端使用传统分页查询
  const {
    data: pageData,
    isLoading: isPageLoading,
    refetch: refetchPage
  } = useQuery<PageResponse>({
    queryKey: listQueryKey,
    queryFn: async () => {
      if (!token || !apiConfig.search) return {
        code: 200,
        success: true,
        data: [],
        total: 0
      };

      const combinedSearchData = {
        ...fixedSearchCondition,
        ...searchData,
      };

      const query: TPageRequest = {
        sort: ["updated_at:desc"],
        pagination: { page: currentPage, pageSize },
        filters: buildSearchFilters(combinedSearchData),
      };

      const result = await requestWithToken<PageResponse>({
        url: apiConfig.search,
        method: "GET",
        data: query,
      });

      if (!result) throw new Error('查询失败');
      
      // 添加序号
      const items = result.data?.map((item, index: number) => ({
        ...item,
        _index: ((result.page as number) - 1) * pageSize + 1 + index,
      })) || [];

      return {
        ...result,
        data: items
      };
    },
    enabled: !isMobile && !!token && !!apiConfig.search,
    staleTime: 3000 // 添加合理的缓存时间
  });


  // 移动端使用无限滚动查询
  const {
    data: infiniteData,
    fetchNextPage,
    hasNextPage,
    isFetchingNextPage,
    isLoading: isInfiniteLoading,
  } = useInfiniteQuery<PageData>({
    queryKey: [...listQueryKey, 'infinite'],
    initialPageParam: 1,
    queryFn: async ({ pageParam }) => {
      if (!token || !apiConfig.search) return {
        code: 200,
        success: true,
        data: [],
        total: 0
      };

      const combinedSearchData = {
        ...fixedSearchCondition,
        ...searchData,
      };

      const query: TPageRequest = {
        sort: ["updated_at:desc"],
        pagination: { page: pageParam as number, pageSize },
        filters: buildSearchFilters(combinedSearchData),
      };

      const result = await requestWithToken<PageData>({
        url: apiConfig.search,
        method: "GET",
        data: query,
      });

      if (!result) throw new Error('查询失败');
      
      // 添加序号
      const items = result.data?.map((item, index: number) => ({
        ...item,
        _index: ((pageParam as number) - 1) * pageSize + 1 + index,
      })) || [];

      return {
        ...result,
        data: items
      };
    },
    getNextPageParam: (lastPage, pages) => {
      if (!lastPage || !lastPage.success || (pages.length * pageSize) >= (lastPage.total ?? 0)) return undefined;
      return pages.length + 1;
    },
    enabled: isMobile && !!token && !!apiConfig.search,
  });

  // 删除操作的 mutation
  const deleteMutation = useMutation<MutationData, Error, any>({
    mutationFn: async (record: any) => {
      if (!apiConfig.delete) throw new Error('删除接口未配置');
      const deleteId = record?._id || record?.id;
      const result = await requestWithToken<MutationData>({
        url: `${apiConfig.delete}?id=${deleteId}`,
        method: "DELETE",
      });
      if (!result) throw new Error('删除失败');
      return result;
    },
    onSuccess: () => {
      message.success("删除成功");
      queryClient.invalidateQueries({ queryKey: listQueryKey });
    },
    onError: (error) => {
      message.error(`删除失败: ${error.message}`);
    },
  });

  // 新增操作的 mutation
  const addMutation = useMutation<MutationData, Error, any>({
    mutationFn: async (values: any) => {
      if (!apiConfig.add) throw new Error('新增接口未配置');
      const result = await requestWithToken<MutationData>({
        url: apiConfig.add,
        method: "POST",
        data: values,
      });
      if (!result) throw new Error('新增失败');
      return result;
    },
    onSuccess: () => {
      message.success("新增成功");
      queryClient.invalidateQueries({ queryKey: listQueryKey });
    },
    onError: (error) => {
      message.error(`新增失败: ${error.message}`);
    },
  });

  // 编辑操作的 mutation
  const editMutation = useMutation<MutationData, Error, any>({
    mutationFn: async (values: any) => {
      if (!apiConfig.edit) throw new Error('编辑接口未配置');
      const editId = values?._id || values?.id;
      const result = await requestWithToken<MutationData>({
        url: `${apiConfig.edit}?id=${editId}`,
        method: "PUT",
        data: values,
      });
      if (!result) throw new Error('编辑失败');
      return result;
    },
    onSuccess: () => {
      message.success("编辑成功");
      queryClient.invalidateQueries({ queryKey: listQueryKey });
    },
    onError: (error) => {
      message.error(`编辑失败: ${error.message}`);
    },
  });

  // 处理搜索
  const handleSearch = (values: any) => {
    setSearchData(values);
    setCurrentPage(1); // 搜索时重置到第一页
    if (isMobile) {
      queryClient.resetQueries({ queryKey: [...listQueryKey, 'infinite'] });
    } else {
      refetchPage();
    }
  };

  // 处理页码变更
  const handlePageChange = (page: number, size?: number) => {
    if (size && size !== pageSize) {
      setPageSize(size);
    }
    setCurrentPage(page);
  };

  // 合并数据
  const allData = useMemo(() => {
    if (isMobile) {
      return infiniteData?.pages.flatMap(page => page?.data ?? []) ?? [];
    }
    return pageData?.data ?? [];
  }, [isMobile, infiniteData, pageData]);
  
  // 计算总数
  const dataTotal = useMemo(() => {
    if (isMobile) {
      return infiniteData?.pages[0]?.total ?? 0;
    }
    return pageData?.total ?? 0;
  }, [isMobile, infiniteData, pageData]);

  // 加载状态
  const isLoading = isMobile ? isInfiniteLoading : isPageLoading;

  const renderSearchForm = () => {
    const handleShowAdd = () => {
      // 如果有自定义新增事件处理函数，则调用自定义函数
      if (props.onCustomAdd) {
        props.onCustomAdd();
      } else {
        // 否则使用默认的弹窗逻辑
        console.log("show add");
        addModalRef.current?.show({} as any);
      }
    };

    const handlePrint = () => {
      setTimeout(() => {
        window.print();
      }, 1000);
    };

    const handleExport = async (searchData: any) => {
      if (apiConfig.search) {
        try {
          let exportCount: number | null = null;

          // 询问用户要导出的数据条数
          await new Promise<void>((resolve, reject) => {
            Modal.confirm({
              title: "请输入要导出的数据条数",
              content: <InputNumber min={1} max={3000} ref={inputRef} />,
              onOk() {
                const value = inputRef.current?.value;
                console.log("value", value);
                if (
                  !value ||
                  isNaN(Number(value)) ||
                  Number(value) <= 0 ||
                  Number(value) > 1000
                ) {
                  message.error("请输入1-3000之间的有效数字");
                  reject();
                } else {
                  exportCount = Number(value);
                  resolve();
                }
              },
              onCancel() {
                reject();
              },
            });
          });

          if (exportCount === null) {
            return; // 用户取消了操作
          }

          const query: TPageRequest = {
            sort: ["updated_at:desc"],
            pagination: { page: 1, pageSize: exportCount },
            filters: buildSearchFilters(searchData),
          };

          const response = await requestWithToken<ApiResponse<Record<string, any>[]>>({
            url: apiConfig.search,
            method: "GET",
            data: query,
          });

          if (response?.code === 200 || response?.success) {
            const workbook = XLSX.utils.book_new();
            const worksheetData: any[] = [];
            const fieldConfig = detailFieldConfig?.length
              ? detailFieldConfig
              : tableColumnConfig;

            // 使用 tableColumnConfig 中的 render 方法处理数据
            response.data?.forEach((record: any) => {
              const row: any = {};
              fieldConfig.forEach((column: any) => {
                const text = record[column.dataIndex];
                row[column.title] = column.render
                  ? column.render(text, record)
                  : text;
              });
              worksheetData.push(row);
            });

            const worksheet = XLSX.utils.json_to_sheet(worksheetData);

            XLSX.utils.book_append_sheet(workbook, worksheet, "导出数据");
            XLSX.writeFile(workbook, "导出数据.xlsx");
            message.success("导出成功");
          } else {
            message.error(response?.error || response.message);
          }
        } catch (error) {
          console.error("导出失败:", error);
          message.error("导出失败");
        }
      }
    };

    const handleBatchAdd = () => {
      const fileInput = document.createElement("input");
      fileInput.type = "file";
      fileInput.accept = ".xlsx,.xls";
      fileInput.style.display = "none";

      fileInput.onchange = async (event: Event) => {
        const target = event.target as HTMLInputElement;
        const file = target.files?.[0];
        if (!file) return;

        const reader = new FileReader();
        reader.onload = async (e) => {
          const data = new Uint8Array(e.target?.result as ArrayBuffer);
          const workbook = XLSX.read(data, { type: "array" });
          const sheetName = workbook.SheetNames[0];
          const worksheet = workbook.Sheets[sheetName];
          const jsonData = XLSX.utils.sheet_to_json(worksheet);
          console.log(jsonData);
          if (apiConfig.import) {
            try {
              const response = await requestWithToken<MutationData>({
                url: apiConfig.import,
                method: "POST",
                data: jsonData,
              });

              if (response?.code === 200 || response?.success) {
                message.success("批量导入成功");
                refetchPage();
              } else {
                message.error(response?.error || response.message);
              }
            } catch (error) {
              console.error("批量导入失败:", error);
              message.error("批量导入失败");
            }
          }
        };
        reader.readAsArrayBuffer(file);

        // 移除文件输入元素
        document.body.removeChild(fileInput);
      };

      document.body.appendChild(fileInput);
      fileInput.click();
    };

    return (
      <Card type="inner" className="mb-4 shadow-sm">
        <SearchForm
          ref={searchFormRef}
          formFieldConfig={props.searchFormFieldConfig}
          onSearch={handleSearch}
          showAddButton={props.enableAdd}
          showExportButton={props.enableExport}
          showBatchAddButton={props.enableImport}
          showPrintButton={props.enablePrint}
          onAdd={handleShowAdd}
          onPrint={handlePrint}
          onExport={handleExport}
          onBatchAdd={handleBatchAdd}
        />
      </Card>
    );
  };

  const renderViewToggle = () => {
    return (
      <Radio.Group
        value={viewType}
        onChange={(e) => setViewType(e.target.value)}
        className="flex bg-white rounded-lg"
        size="small"
      >
        <Tooltip title="表格视图">
          <Radio.Button value="table" className="px-2">
            <TableOutlined />
          </Radio.Button>
        </Tooltip>
        <Tooltip title="列表视图">
          <Radio.Button value="list" className="px-2">
            <AppstoreOutlined />
          </Radio.Button>
        </Tooltip>
      </Radio.Group>
    );
  };

  const renderListView = (columnConfig: TableColumnConfig[]) => {
    const handleShowDetail = (record: any) => {
      detailModalRef.current?.show(record);
    };

    const handleShowEdit = (record: any) => {
      // 如果有自定义编辑事件处理函数，则调用自定义函数
      if (props.onCustomEdit) {
        props.onCustomEdit(record);
      } else {
        // 否则使用默认的弹窗逻辑
        editModalRef.current?.show(record);
      }
    };

    // const allData = infiniteData?.pages.flatMap(page => page.data) || [];
    // const dataTotal = infiniteData?.pages[0]?.total || 0;

    return (
      <Card
        type="inner"
        className="shadow-sm"
        styles={{
          body: { padding: "16px" },
        }}
        extra={renderViewToggle()}
      >
        {isMobile ? (
          <InfiniteScroll
            loadMore={() => fetchNextPage()}
            hasMore={!!hasNextPage}
            isLoading={isLoading || isFetchingNextPage}
            currentPage={currentPage}
            totalItems={dataTotal}
          >
            <ListItems
              columns={columnConfig}
              dataSource={allData}
              loading={isLoading}
              onDetail={handleShowDetail}
              onEdit={handleShowEdit}
              onDelete={confirmDelete}
              enableEdit={props.enableEdit}
              enableDelete={props.enableDelete}
              isMobile={isMobile}
              extraButtonMenu={props.extraButtonMenu}
              onRowClick={props.onRowClick}
            />
          </InfiniteScroll>
        ) : (
          <ListItems
            columns={columnConfig}
            dataSource={allData}
            loading={isLoading}
            onDetail={handleShowDetail}
            onEdit={handleShowEdit}
            onDelete={confirmDelete}
            enableEdit={props.enableEdit}
            enableDelete={props.enableDelete}
            isMobile={isMobile}
            extraButtonMenu={props.extraButtonMenu}
            onRowClick={props.onRowClick}
            pagination={{
              current: currentPage,
              pageSize,
              total: dataTotal,
              onChange: handlePageChange,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total: number) => `共 ${total} 项`,
            }}
          />
        )}
      </Card>
    );
  };

  const confirmDelete = (record: any) => {
    Modal.confirm({
      title: "确定要删除吗？",
      onOk: () => {
        handleDelete(record);
      },
    });
  };

  const renderTable = (columnConfig: TableColumnConfig[]) => {
    const handleShowDetail = (record: any) => {
      detailModalRef.current?.show(record);
    };

    const handleShowEdit = (record: any) => {
      // 如果有自定义编辑事件处理函数，则调用自定义函数
      if (props.onCustomEdit) {
        props.onCustomEdit(record);
      } else {
        // 否则使用默认的弹窗逻辑
        editModalRef.current?.show(record);
      }
    };

    const extraButtonMenu = (record: any) => {
      const menus = [] as any[];

      // 添加自定义扩展按钮
      if (props.extraButtonMenu) {
        menus.push(...props.extraButtonMenu(record));
      }

      // 添加默认按钮
      if (props.enableEdit) {
        menus.push({
          key: 'edit',
          label: '编辑',
          onClick: () => handleShowEdit(record)
        });
      }

      if (props.enableDelete) {
        menus.push({
          key: 'delete',
          label: '删除',
          onClick: () => confirmDelete(record)
        });
      }

      return menus;
    };

    return (
      <Card
        type="inner"
        className="shadow-sm"
        extra={renderViewToggle()}
        styles={{
          body: { padding: "16px" },
        }}
      >
        <ListTable
          columns={columnConfig}
          dataSource={allData}
          onExtraButtonClick={handleShowDetail}
          pagination={{
            current: currentPage,
            pageSize,
            total: dataTotal,
            onChange: handlePageChange,
          }}
          loading={isLoading}
          extraButtonMenu={extraButtonMenu}
          onTableChange={() => {}}
          onRowClick={props.onRowClick}
        />
      </Card>
    );
  };

  const renderDetail = (detailConfig: DetailFieldConfig[]) => {
    // 根据detailConfig渲染详情
    return (
      <DetailModal
        ref={detailModalRef}
        detailConfig={detailConfig}
        detailComponent={props.detailComponent}
        modalWidth={props.detailModalWidth}
      />
    );
  };

  // 新增弹窗
  const renderAddModal = () => {
    const handleAdd = async (values: any, callback: () => void) => {
      try {
        await addMutation.mutateAsync(values);
        callback?.();
      } catch (error) {
        // 错误已经在 mutation 中处理
      }
    };
    return (
      <AddModal
        ref={addModalRef}
        formItemConfigs={props.addFormFieldConfig ?? []}
        onOk={handleAdd}
        modalFormNode={props.addFormNode}
        modalWidth={props.addModalWidth}
      />
    );
  };

  // 编辑弹窗
  const renderEditModal = () => {
    const handleEdit = async (values: any, callback: () => void) => {
      try {
        await editMutation.mutateAsync(values);
        callback?.();
      } catch (error) {
        // 错误已经在 mutation 中处理
      }
    };
    return (
      <EditModal
        ref={editModalRef}
        formItemConfigs={props.editFormFieldConfig ?? []}
        onOk={handleEdit}
        modalFormNode={props.editFormNode}
        modalWidth={props.editModalWidth}
      />
    );
  };

  // 处理删除
  const handleDelete = async (record: any) => {
    await deleteMutation.mutateAsync(record);
  };

  // 组件加载时触发搜索
  useEffect(() => {
    if (searchFormRef.current) {
      searchFormRef.current.submitForm();
    }
  }, []);

  return (
    <div className="p-4 space-y-4">
      {renderSearchForm()}
      {viewType === "table"
        ? renderTable(tableColumnConfig)
        : renderListView(tableColumnConfig)}
      {renderDetail(detailFieldConfig)}
      {renderAddModal()}
      {renderEditModal()}
    </div>
  );
};

export default Manager;
